import smtplib
import json
import os
from models.mail_model import Mail
from email.mime.text import MIMEText
from email.header import Header

def load_settings():
    """加载配置文件"""
    base_dir = os.path.dirname(os.path.abspath(__file__))
    config_path = os.path.join(base_dir, "../config/settings.json")
    with open(config_path) as f:
        return json.load(f)

def send_email_service(mail: Mail):
    """发送邮件的具体实现"""
    settings = load_settings()
    try:
        with smtplib.SMTP_SSL(settings["smtp_server"], settings["smtp_port"]) as server:
            server.login(settings["username"], settings["password"])
            
            # 使用 MIMEText 构造支持中文的邮件内容
            message = MIMEText(mail.content, 'plain', 'utf-8')
            message['Subject'] = Header(mail.subject, 'utf-8')
            message['From'] = settings["from_email"]
            message['To'] = mail.to_email
            if mail.cc_email:
                message['Cc'] = mail.cc_email
            
            # 发送邮件
            recipients = [mail.to_email] + ([mail.cc_email] if mail.cc_email else [])
            server.sendmail(settings["from_email"], recipients, message.as_string())
    except Exception as e:
        print(f"邮件发送失败，原因: {str(e)}")  # 输出问题原因
        raise Exception(f"Failed to send email: {str(e)}")